<template>
  <div class="box">
    <div class="content_top">
      <!-- <img
        src="../assets/logo-study.png"
        alt=""
        style="width: 300px; height: 100px"
      /> -->
      <h6>权限管理系统测试</h6>
    </div>
    <div class="content_host">
      <h6>用户登录</h6>
      <a-form
        :model="ruleForm"
        :rules="rules"
        ref="formRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <a-form-item
          label="用户名"
          name="usermobile"
          label-width="100px"
          style="color: #ffffff; margin: 20px"
        >
          <a-input
            v-model:value="ruleForm.usermobile"
            autocomplete="off"
          ></a-input>
        </a-form-item>
        <a-form-item
          label="密码"
          name="userpwd"
          label-width="100px"
          style="color: #ffffff; margin: 20px"
        >
          <a-input-password
            type="password"
            v-model:value="ruleForm.userpwd"
            autocomplete="off"
          ></a-input-password>
        </a-form-item>
      </a-form>
      <a-button type="primary" @click="submitForm" style="margin: 20px"
        >登录</a-button
      >
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed } from "vue";
import { Form, Input, Button, message } from "ant-design-vue";
import axios from "axios";
import { useRouter, useRoute } from "vue-router";
import { anyType } from "ant-design-vue/es/_util/type";
import { useStore } from "vuex";
// const store = useStore();
import { generateDynamicRoutes } from "@/router";
import http from "../http/http";
import { Item } from "ant-design-vue/es/menu";

const store = useStore();
const router = useRouter();
const route = useRoute();

// 检查当前用户角色的操作---可以放在一个js文件中导入。这里直接写入这个文件

// function filterRoutesByRole(routes: any[], userRoles: string[]) {
//   return routes.filter((route) => {
//     // 如果没有设置roles，或者用户角色包含任一所需角色
//     return (
//       !route.meta?.roles ||
//       route.meta.roles.some((role: string) => userRoles.includes(role))
//     );
//   });
// }
/*
function filterRoutesByRole(routes: any[], userRoles: string[]): any[] {
  return routes
    .map((route) => {
      // 复制路由对象避免修改原始数据
      const filteredRoute = { ...route };

      // 处理子路由（递归）
      if (route.children && route.children.length > 0) {
        filteredRoute.children = filterRoutesByRole(route.children, userRoles);
      }

      return filteredRoute;
    })
    .filter((route) => {
      // 过滤条件：无权限要求 或 有权限且用户有权限
      return (
        !route.meta?.roles ||
        route.meta.roles.some((role: string) => userRoles.includes(role))
      );
    });
}

function generateDynamicRoutes() {
  const userRoles = store.state.roles || [];
  console.log(userRoles);
  const accessibleRoutes = filterRoutesByRole(dynamicRoutes, userRoles);

  // 先移除可能已存在的动态路由
  router.getRoutes().forEach((r) => {
    if (dynamicRoutes.some((dr) => dr.name === r.name)) {
      router.removeRoute(r.name!);
    }
  });

  // 添加新路由
  accessibleRoutes.forEach((route) => {
    console.log("route>>>>>>>>>>", route);
    // const parent_path = route.path
    router.addRoute(route);
    // if (route.children && route.children.length > 0) {
    //   route.children.map((route: any) => {
    //     const itemroute = {
    //       ...route,
    //       path:route.meta.title_path,
    //     }
    //     console.log("route>>>>>>>>>>", itemroute);
    //     router.addRoute(itemroute);
    //   });
    // }
  });
  console.log("accessibleRoutes>>>>>>>>>", accessibleRoutes);
  // 4. 确保添加404路由（关键！）
  // router.addRoute({
  //   path: "/:pathMatch(.*)*",
  //   name: "NotFound",
  //   component: () => import("@/views/NotFound.vue"),
  // });
}
*/
// 完结...

const formRef = ref();
const ruleForm = ref({
  usermobile: "",
  userpwd: "",
});

const rules = {
  usermobile: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    {
      min: 2,
      max: 15,
      message: "用户名长度在 2 到 15 个字符",
      trigger: "blur",
    },
  ],
  userpwd: [
    { required: true, message: "请输入密码", trigger: "blur" },
    {
      min: 6,
      max: 20,
      message: "密码长度在 6 到 20 个字符",
      trigger: "blur",
    },
  ],
};
// 获取用户对应的权限
const userPermiss = async () => {
  try {
    const results = await http.get("/api/users/userPermiss");
    const userPermiss = results.data.results;
    console.log('获取用户对应的权限::',userPermiss)
    // 将用户权限存到vuex中
    store.commit("SET_PERMISS", userPermiss);
  } catch (error) {
    console.log(error);
    message.error(error.response.data.message);
  }
};

// 登录按钮
const submitForm = async () => {
  try {
    // 尝试对表单进行验证，如果验证不通过，则不会执行后续代码
    await formRef.value?.validate();

    // 使用 axios 发送 POST 请求到服务器的登录接口
    // 将用户名和密码作为请求体发送
    const response = await axios.post("/api/users/login", {
      username: ruleForm.value.usermobile, // 用户名字段在请求体中
      password: ruleForm.value.userpwd, // 密码字段在请求体中
    });

    // 打印响应对象到控制台
    console.log(response);

    // 弹出响应消息提示用户
    message.info(response.data.msg);
    // alert(response.data.msg);

    // 从响应数据中提取 token、用户 ID 和用户名
    const token = response.data.data.token;
    const userid = response.data.data.userInfo.id;
    const username = response.data.data.userInfo.username;
    const roleid = response.data.data.userInfo.role_id;
    const role_code: string = response.data.data.userInfo.role_code; // 角色的唯一标识

    // 将 token、用户 ID 和用户名存储到本地存储（localStorage）
    localStorage.setItem("token", token);
    localStorage.setItem("userid", userid);
    localStorage.setItem("username", username);
    localStorage.setItem("roleid", roleid);
    localStorage.setItem("role_code", role_code);
    localStorage.setItem("token_is_exp", "0");

    let role_code_arr = ref<string[]>([]);
    role_code_arr.value.push(role_code);
    // 将角色的编码存到vuex中
    store.commit("SET_ROLES", role_code_arr);
    // 登录成功的时候获取用户对应权限
    // 1. 先获取权限（确保权限加载完成）
    await userPermiss(); // 使用 await 确保权限加载完成
    // 2. 生成动态路由（依赖权限数据）
    await generateDynamicRoutes(); // 如果 generateDynamicRoutes 是异步的，也要 await

    // 如果 token 存在，则跳转到后台首页
    if (token) {
      router.push("admin/user").catch((error) => {
        console.log(error); // 如果路由跳转失败，则打印错误信息
      });
    }
    
    // 打印 token 到控制台，用于调试
    console.log(token);
  } catch (error: any) {
    // 如果请求失败或验证失败，则捕获错误并打印到控制台
    console.error("请求失败:", error);
    message.error(error.response.data.msg);
  }
};
onMounted(() => {
  // userPermiss()
});
</script>

<style scoped>
/* ... Your CSS styles remain the same ... */
.box {
  background: linear-gradient(
    135deg,
    #416bd4 0%,
    #4e22a1 100%
  ); /* 渐变背景 */ /* 替换为背景颜色 */
  /* background: url("../assets/login-back.jpg"); */
  width: 100%;
  height: 100vh;
}
.content_host {
  width: 450px;
  margin: auto;
}
.content_host > button {
  width: 450px;
  background-color: #007dfe;
  color: #ffffff;
  height: 40px;
  border-radius: 10px;
  font-size: 18px;
  margin: 20px 0;
}
.content_host > p {
  display: flex;
  justify-content: space-between;
  margin: 20px 0;
}
.content_host > p > span {
  font-size: 24px;
  color: #ffffff;
  font-family: SourceHanSerifsc Bold;
}
.content_host > p > input {
  background-color: #ffffff;
  width: 338px;
  height: 40px;
  border-radius: 10px;
}
.content_host > h6 {
  font-size: 24px;
  color: #ffffff;
  font-family: SourceHanSerifsc Bold;
  text-align: center;
  margin: 20px 0;
}
.content_top {
  display: flex;
  justify-content: space-between;
}
.content_top > img {
  margin-top: 40px;
  margin-left: 40px;
}
.content_top > h6 {
  margin-top: 40px;
  margin-right: 40px;
  font-family: SourceHanSerifsc Bold;
  font-size: 24px;
  color: #ffffff;
}
</style>